#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- This's Email Util
# -- 邮件发送服务，部分需要结合自身App做调整
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2018年3月2日 12:23:29
# ----------------------------------------------------------
from flask import render_template
from flask_mail import Message
# TODO 需要结合自身App做调整
from core.app import mail, email, app
from core.utils.decorators import async


@async
def send_async_email(app, msg):
    """
        Send Async Email
        -- 异步发送邮件

        :param app: app
        :param msg: msg
        :return:    None
    """
    with app.app_context():
        mail.send(msg)


def send_email(subject, sender, recipients, text_body, html_body):
    """
        Send Email
        -- 发送邮件

        :param subject:     主题
        :param sender:      寄件人
        :param recipients:  收件人
        :param text_body:   plain text message
        :param html_body:   HTML message
        :return:            None
    """
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    send_async_email(app, msg)


def follower_notification(followed, follower):
    """
        Follower Notification
        -- 关注提醒

        :param followed:    followed
        :param follower:    follower
        :return:            None
    """
    send_email("[microblog] %s is now following you!" % follower.nickname,
               email["MAIL_USERNAME"], [followed.email],
               render_template("follower_email.txt", user=followed, follower=follower),
               render_template("follower_email.html", user=followed, follower=follower))
